package com.dzpk.facadeserver.net;

import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.transport.socket.AbstractSocketSessionConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import somnus.net.DefaultHandler;
import somnus.net.message.IMessage;

/**
 * web连过来的
 */
public class FacadeHandler extends DefaultHandler {

    public FacadeHandler(String name) {
        super(name);
    }

    private final static Logger log = LoggerFactory.getLogger(FacadeHandler.class);

    private static long sessionCount;

    @Override
    public void handleMessage(IoSession session, Object message) throws Exception {

        log.info("facadeServerHandler messageReceived....");
        IMessage b = (IMessage) message;
        setTcpNodelay(session, true);
        Dispatcher.dispatch(session, b);
    }



    @Override
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        log.info("facade sessionIdle id =" + session.getId());
        if (session != null) {
            session.close(true);
        }
    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
        log.info("facade close id =" + session.getId());
        sessionCount--;
    }

    @Override
    public void sessionCreated(IoSession session) throws Exception {
        log.info("facade create session id =" + session.getId() + " login ip " + session.getRemoteAddress());
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        log.error(String.format("facade server handler exception %s", session.getId()), cause);
    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {
    }

    public void destroy() {
        log.info(String.format("facade destroy server handler"));

    }

    public void setTcpNodelay(IoSession session, boolean tcpNodelay) {
        if (session != null) {
            AbstractSocketSessionConfig s = (AbstractSocketSessionConfig) session.getConfig();
            if (s.isTcpNoDelay() ^ tcpNodelay) {
                s.setTcpNoDelay(tcpNodelay);
            }
        }
    }
}
